package com.tpc.control.bean;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Vector;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;

import org.richfaces.model.ScrollableTableDataModel.SimpleRowKey;
import org.richfaces.model.selection.SimpleSelection;

import com.sap.conn.jco.JCoException;
import com.tpc.control.jpa.CommonData;
import com.tpc.control.jpa.CommonDataDAO;
import com.tpc.control.jpa.CommonDataId;
import com.tpc.control.jpa.EntityManagerHelper;
import com.tpc.control.jpa.ReserveHeader;
import com.tpc.control.jpa.ReserveHeaderDAO;
import com.tpc.control.jpa.ReserveItem;
import com.tpc.control.jpa.ReserveItemDAO;
import com.tpc.control.jpa.ReserveItemGreige;
import com.tpc.control.jpa.ReserveItemGreigeDAO;
import com.tpc.control.jpa.ReserveItemId;
import com.tpc.control.jpa.ReserveItemLab;
import com.tpc.control.jpa.ReserveItemLabAnswer;
import com.tpc.control.jpa.ReserveItemLabAnswerId;
import com.tpc.control.jpa.ReserveItemLabId;
import com.tpc.control.jpa.ReserveItemSale;
import com.tpc.control.jpa.ReserveItemSaleDAO;
import com.tpc.control.jpa.ReserveItemSaleGreige;
import com.tpc.control.jpa.ReserveItemSaleId;
import com.tpc.control.jpa.SaleData;
import com.tpc.control.jpa.SaleDataDAO;
import com.tpc.control.jpa.SaleDataId;
import com.tpc.control.sap.SapConnector;
import com.tpc.control.sap.ZBapiGetCustomerList;
import com.tpc.control.util.Formatting;
import com.tpc.control.util.GenerateList;
import com.tpc.control.util.MessageUtil;

public class Con100 {
	private final static String SAP_HOST = "192.168.42.188";
	private String reserveNo;
	private ReserveHeader reserve;
	private List<ReserveItem> reserveItems;
	private List<ReserveItemLab> labItems;
	private List<ReserveItemGreige> greigeItems;
	private List<ReserveItemSaleGreige> saleItems;

	private List<CommonData> dyeItems;

	private List<ReserveItemLabAnswer> labAnswerItems;
	private List<ReserveItemLabAnswer> labAnswerItemsBefore;

	private ReserveItem selectItem;
	private ReserveItem insertItem;
	private ReserveItemLab insertLabItem;
	private ReserveItemGreige insertGreigeItem;
	private ReserveItemSale insertSaleItem;
	private ReserveItemLab selectLabItem;
	private ReserveItemSaleGreige selectSaleItem;
	private ReserveItemGreige selectGreigeItem;
	private CommonData selectDyeItem;

	private SimpleSelection selection = new SimpleSelection();
	private SimpleSelection selectionSale = new SimpleSelection();
	private SimpleSelection selectionLab = new SimpleSelection();
	private SimpleSelection selectionGreige = new SimpleSelection();
	private SimpleSelection selectionDye = new SimpleSelection();
	private int labCurrentRow;

	private ArrayList<ReserveItem> selectedItems = new ArrayList<ReserveItem>();
	
	private Vector productionList;
	private Vector divisionList;
	private Vector statusList;
	private Vector uomList;

	private boolean created;
	private boolean changed;
	
	private boolean editLine;
	private boolean editLab;
	private boolean editRaw;
	private boolean editGreige;
	private boolean editSale;
	private boolean editDye;
	private Timestamp lastChangeDate;
	private List<ReserveItemGreige> greigeDeletes;
	private List<ReserveItemSaleGreige> saleDeletes;
	
	public ReserveItemGreige getSelectGreigeItem() {
		return selectGreigeItem;
	}
	public void setSelectGreigeItem(ReserveItemGreige selectGreigeItem) {
		this.selectGreigeItem = selectGreigeItem;
	}
	public CommonData getSelectDyeItem() {
		return selectDyeItem;
	}
	public void setSelectDyeItem(CommonData selectDyeItem) {
		this.selectDyeItem = selectDyeItem;
	}
	
	public SimpleSelection getSelectionGreige() {
		return selectionGreige;
	}
	public void setSelectionGreige(SimpleSelection selectionGreige) {
		this.selectionGreige = selectionGreige;
	}
	public SimpleSelection getSelectionDye() {
		return selectionDye;
	}
	public void setSelectionDye(SimpleSelection selectionDye) {
		this.selectionDye = selectionDye;
	}
	public ReserveItemSaleGreige getSelectSaleItem() {
		return selectSaleItem;
	}
	public void setSelectSaleItem(ReserveItemSaleGreige selectSaleItem) {
		this.selectSaleItem = selectSaleItem;
	}
	public int getLabCurrentRow() {
		return labCurrentRow;
	}
	public void setLabCurrentRow(int labCurrentRow) {
		this.labCurrentRow = labCurrentRow;
	}
	public ReserveItemLab getSelectLabItem() {
		return selectLabItem;
	}
	public void setSelectLabItem(ReserveItemLab selectLabItem) {
		this.selectLabItem = selectLabItem;
	}
	public List<ReserveItemLabAnswer> getLabAnswerItemsBefore() {
		return labAnswerItemsBefore;
	}
	public void setLabAnswerItemsBefore(
			List<ReserveItemLabAnswer> labAnswerItemsBefore) {
		this.labAnswerItemsBefore = labAnswerItemsBefore;
	}
	public List<ReserveItemLabAnswer> getLabAnswerItems() {
		return labAnswerItems;
	}
	public void setLabAnswerItems(List<ReserveItemLabAnswer> labAnswerItems) {
		System.out.println("setLabAnswerItems");
		this.labAnswerItems = labAnswerItems;
		setLabAnswerItemsBefore(new ArrayList());
		for(int i=0;i<labAnswerItems.size();i++) {
			ReserveItemLabAnswer aAnswer = labAnswerItems.get(i);
			this.getLabAnswerItemsBefore().add(new ReserveItemLabAnswer(aAnswer.getId(), aAnswer.getReserveItem(), aAnswer.getReserveItemLab(), aAnswer.getReserveLabDate(), aAnswer.getRemark(), aAnswer.getCreateDate(), aAnswer.getCreateBy()));
		}
	}
	public boolean isEditLine() {
		return editLine;
	}
	public void setEditLine(boolean editLine) {
		this.editLine = editLine;
	}
	public boolean isCreated() {
		return created;
	}
	public void setCreated(boolean created) {
		this.created = created;
	}
	public boolean isChanged() {
		return changed;
	}
	public void setChanged(boolean changed) {
		this.changed = changed;
	}
	public boolean isEditLab() {
		return editLab;
	}
	public void setEditLab(boolean editLab) {
		this.editLab = editLab;
	}
	public boolean isEditRaw() {
		return editRaw;
	}
	public void setEditRaw(boolean editRaw) {
		this.editRaw = editRaw;
	}
	public boolean isEditGreige() {
		return editGreige;
	}
	public void setEditGreige(boolean editGreige) {
		this.editGreige = editGreige;
	}
	public boolean isEditSale() {
		return editSale;
	}
	public void setEditSale(boolean editSale) {
		this.editSale = editSale;
	}
	public boolean isEditDye() {
		return editDye;
	}
	public void setEditDye(boolean editDye) {
		this.editDye = editDye;
	}
	public SimpleSelection getSelectionLab() {
		return selectionLab;
	}
	public void setSelectionLab(SimpleSelection selectionLab) {
		this.selectionLab = selectionLab;
	}
	public SimpleSelection getSelectionSale() {
		return selectionSale;
	}
	public void setSelectionSale(SimpleSelection selectionSale) {
		this.selectionSale = selectionSale;
	}
	public Vector getProductionList() {
		return productionList;
	}
	public void setProductionList(Vector productionList) {
		this.productionList = productionList;
	}
	public Vector getUomList() {
		return uomList;
	}
	public void setUomList(Vector uomList) {
		this.uomList = uomList;
	}
	public Vector getStatusList() {
		return statusList;
	}
	public void setStatusList(Vector statusList) {
		this.statusList = statusList;
	}
	public Vector getDivisionList() {
		return divisionList;
	}
	public void setDivisionList(Vector divisionList) {
		this.divisionList = divisionList;
	}
	public ReserveItemSale getInsertSaleItem() {
		return insertSaleItem;
	}
	public void setInsertSaleItem(ReserveItemSale insertSaleItem) {
		this.insertSaleItem = insertSaleItem;
	}
	public ReserveItemGreige getInsertGreigeItem() {
		return insertGreigeItem;
	}
	public void setInsertGreigeItem(ReserveItemGreige insertGreigeItem) {
		this.insertGreigeItem = insertGreigeItem;
	}
	public ReserveItemLab getInsertLabItem() {
		return insertLabItem;
	}
	public void setInsertLabItem(ReserveItemLab insertLabItem) {
		this.insertLabItem = insertLabItem;
	}
	public List<CommonData> getDyeItems() {
		return dyeItems;
	}
	public void setDyeItems(List<CommonData> dyeItems) {
		this.dyeItems = dyeItems;
	}
	public List<ReserveItemLab> getLabItems() {
		return labItems;
	}
	public void setLabItems(List<ReserveItemLab> labItems) {
		this.labItems = labItems;
	}
	public List<ReserveItemGreige> getGreigeItems() {
		return greigeItems;
	}
	public void setGreigeItems(List<ReserveItemGreige> greigeItems) {
		this.greigeItems = greigeItems;
	}
	public List<ReserveItemSaleGreige> getSaleItems() {
		return saleItems;
	}
	public void setSaleItems(List<ReserveItemSaleGreige> saleItems) {
		this.saleItems = saleItems;
	}
	public ArrayList<ReserveItem> getSelectedItems() {
		return selectedItems;
	}
	public void setSelectedItems(ArrayList<ReserveItem> selectedItems) {
		this.selectedItems = selectedItems;
	}
	public SimpleSelection getSelection() {
		return selection;
	}
	public void setSelection(SimpleSelection selection) {
		this.selection = selection;
	}
	public ReserveItem getInsertItem() {
		return insertItem;
	}
	public void setInsertItem(ReserveItem insertItem) {
		this.insertItem = insertItem;
	}
	public ReserveItem getSelectItem() {
		return selectItem;
	}
	public void setSelectItem(ReserveItem selectItem) {
		this.selectItem = selectItem;
	}
	public String getReserveNo() {
		if (reserveNo != null) {
			return reserveNo.toUpperCase();
		} else {
			return reserveNo;
		}
	}
	public void setReserveNo(String reserveNo) {
		this.reserveNo = reserveNo;
	}
	public ReserveHeader getReserve() {
		return reserve;
	}
	public void setReserve(ReserveHeader reserve) {
		this.reserve = reserve;
	}
	public List<ReserveItem> getReserveItems() {
		return reserveItems;
	}
	public void setReserveItems(List<ReserveItem> reserveItems) {
		this.reserveItems = reserveItems;
	}
	
	public String gotoCon100() {
		return "con100";
	}
	
	private void initData() {
		selectItem = new ReserveItem();
		initTableData();
		divisionList = GenerateList.generateDivisionSelectItems();
		statusList = GenerateList.generateReserveStatusSelectItems();
		uomList = GenerateList.generateUOMSelectItems();
		productionList = new Vector();
		this.setEditLine(false);
		this.setEditLab(false);
		this.setEditRaw(false);
		this.setEditGreige(false);
		this.setEditSale(false);
		this.setEditDye(false);
	}
	
	private void initTableData() {
		labItems = new ArrayList();
		greigeItems = new ArrayList();
		saleItems = new ArrayList();
		dyeItems = new ArrayList();
		greigeDeletes = new ArrayList();
		saleDeletes = new ArrayList();
	}
	
	public String searchReserve() {
		System.out.println("con100:searchReserve");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		EntityManager em = EntityManagerHelper.getEntityManager();
		if (getReserveNo() == null || getReserveNo().equals("")) {
			FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error06"));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con100Form", facesMessage);
			return null;
		}
		
		try {
			em.clear();
			ReserveHeaderDAO headerDAO = new ReserveHeaderDAO();
			ReserveHeader aHeader = headerDAO.findById(getReserveNo());
			if (aHeader != null) {
				aHeader.setReserveNo(getReserveNo());
				em.refresh(aHeader);
				reserve = aHeader;
				reserveItems = aHeader.retrieveItemsAll();
				lastChangeDate = new Timestamp(reserve.getChangeDate().getTime());
				changed = true;
				created = !changed;
				initData();
				return "con101";
			} else {
				FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error02"));
				facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
				facesContext.addMessage("con100Form", facesMessage);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error08"));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con100Form", facesMessage);
			return null;
		}
	}
	
	public String createReserve() {
		System.out.println("con100:createReserve");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		EntityManager em = EntityManagerHelper.getEntityManager();
		if (getReserveNo() == null || getReserveNo().equals("")) {
			FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error05"));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con100Form", facesMessage);
			return null;
		}
		
		try {
			ReserveHeaderDAO headerDAO = new ReserveHeaderDAO();
			ReserveHeader aHeader = headerDAO.findById(getReserveNo());
			if (aHeader == null) {
				reserve = new ReserveHeader();
				reserve.setReserveNo(getReserveNo());
				reserve.setCreateDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
				reserve.setCreateBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
				reserveItems = new ArrayList();
				changed = false;
				created = !changed;
				initData();
				return "con101";
			} else {
				FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error03"));
				facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
				facesContext.addMessage("con100Form", facesMessage);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error08"));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con100Form", facesMessage);
			return null;
		}
	}
	
	public void selectReserveLineEvent(ActionEvent event) {
		System.out.println("con100:selectReserveLineEvent");
		this.getSelectedItems().clear();
		Iterator<Object> iterator = getSelection().getKeys();
		while (iterator.hasNext()) {
			SimpleRowKey key = (SimpleRowKey) iterator.next();
//			Integer key = (Integer) iterator.next();
			getSelectedItems().add(reserveItems.get(key.intValue()));
			System.out.println(key);
		}

		selectItem = new ReserveItem();
		// routings = new Vector();
		if (getSelectedItems().size() > 0) {
			selectItem = getSelectedItems().get(0);
			labItems = selectItem.retrieveReserveItemLabsSort();
			greigeItems = selectItem.retrieveReserveItemGreigesSort();
			System.out.println("greigeItems: "+greigeItems.size());
			List<ReserveItemSale> saleItemList = selectItem.retrieveReserveItemSalesSort();
			
			dyeItems = selectItem.retrieveDyeProductions();
			System.out.println("dyeItems: "+dyeItems.size());
			productionList = new Vector();
			SelectItem itemNull = new SelectItem("","");
			productionList.addElement(itemNull);
			for (int i=0;i<greigeItems.size();i++) {
				ReserveItemGreige aGreige = greigeItems.get(i);
				SelectItem item = new SelectItem(aGreige.getCommonData().getId().getProductionNo(),aGreige.getCommonData().getId().getProductionNo());
				productionList.addElement(item);
			}
			saleItems = new ArrayList();
			for (int i=0;i<saleItemList.size();i++) {
				ReserveItemSale aSale = saleItemList.get(i);
				ReserveItemSaleGreige aSaleGreige = new ReserveItemSaleGreige();
				aSaleGreige.setReserveItemSale(aSale);
				CommonDataId aCommonId;
				if (aSale.getReserveItemGreige() != null) {
					aCommonId = new CommonDataId(aSale.getReserveItemGreige().getCommonData().getId().getProductionNo(), aSale.getReserveItemGreige().getCommonData().getId().getSeq());
				} else {
					aCommonId = new CommonDataId("", "");
				}
				aSaleGreige.setCommonDataId(aCommonId);
				saleItems.add(aSaleGreige);
			}
			this.setEditLine(true);
			this.setEditLab(true);
			this.setEditRaw(true);
			this.setEditGreige(true);
			this.setEditSale(true);
			this.setEditDye(true);
		}
	}
	
	public void insertReserveLineOpen(ActionEvent event) {
		System.out.println("con100:insertReserveLineOpen");
		insertItem = new ReserveItem();
	}
	public String insertReserveLineSave() {
		System.out.println("con100:insertReserveLineSave");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		
		ReserveItemId id = new ReserveItemId();
		id.setReserveNo(reserve.getReserveNo());
		if (reserveItems.size() > 0) {
			ReserveItem aItem = reserveItems.get(reserveItems.size()-1);
			id.setReserveLine(aItem.getId().getReserveLine()+1);
		} else {
			id.setReserveLine(1);
		}
		insertItem.setMaterialNo(insertItem.getMaterialNo().toUpperCase());
		insertItem.setMaterialDesign(insertItem.getMaterialDesign().toUpperCase());
		insertItem.setCreateDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
		insertItem.setCreateBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
		insertItem.setId(id);
		reserveItems.add(insertItem);
		insertItem = new ReserveItem();
		return null;
	}
	public void onchangeReserveItem(ActionEvent event) {
		System.out.println("con100:onchangeReserveItem");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		selectItem.setChangeDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
		selectItem.setChangeBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
	}
	public void selectReserveLabLineEvent(ActionEvent event) {
		System.out.println("con100:selectReserveLabLineEvent");
//		System.out.println("getLabCurrentRow: "+this.getLabCurrentRow());
		if (selectLabItem!=null) {
			System.out.println("selectLabItem.getId().getReserveLabNo(): "+selectLabItem.getId().getReserveLabNo());
		}
//		System.out.println("getLabCurrentRow: "+this.getLabCurrentRow());
//		selectLabItem = labItems.get(this.getLabCurrentRow());
	}
	
	public void insertReserveLineLabOpen(ActionEvent event) {
		System.out.println("con100:insertReserveLineLabOpen");
		insertLabItem = new ReserveItemLab();
	}
	
	public String insertReserveLineLabSave() {
		System.out.println("con100:insertReserveLineLabSave");
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		
		ReserveItemLabId id = new ReserveItemLabId();
		id.setReserveNo(reserve.getReserveNo());
		id.setReserveLine(selectItem.getId().getReserveLine());
		if (labItems.size() > 0) {
			ReserveItemLab aItem = labItems.get(labItems.size()-1);
			id.setReserveLabNo(aItem.getId().getReserveLabNo()+1);
		} else {
			id.setReserveLabNo(1);
		}
		insertLabItem.setId(id);
		if (insertLabItem.getStandardDate() != null) {
			insertLabItem.setConfirmLabPlan(new Date(insertLabItem.getStandardDate().getTime() + (7*24*60*60*1000)));
		}
		insertLabItem.setCreateDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
		insertLabItem.setCreateBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
		labItems.add(insertLabItem);
		selectItem.getReserveItemLabs().add(insertLabItem);
		selectItem.setLabChangeDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
		selectItem.setLabChangeBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
		insertLabItem = new ReserveItemLab();

		return null;
	}
	
	public void onchangeReserveLineLab(ActionEvent event) {
		System.out.println("con100:onchangeReserveLineLab");
		selectLabItem = labItems.get(((SimpleRowKey)getSelectionLab().getKeys().next()).intValue());
		setLabAnswerItems(selectLabItem.retrieveReserveItemLabAnswersSort());
	}
	public void selectReserveLabAnswerLineEvent(ActionEvent event) {
		System.out.println("con100:selectReserveLabAnswerLineEvent");
/*		Iterator<Object> iterator = getSelectionLab().getKeys();
		labAnswerItems = new ArrayList();
		while (iterator.hasNext()) {
			SimpleRowKey key = (SimpleRowKey) iterator.next();
			System.out.println(key.intValue());
			selectLabItem = labItems.get(key.intValue());
			labAnswerItems = selectLabItem.getReserveItemLabAnswersSort();
			break;
		}*/
//		System.out.println("getLabCurrentRow: "+this.getLabCurrentRow());
//		selectLabItem = labItems.get(this.getLabCurrentRow());
//		System.out.println("getLabCurrentRow: "+this.getLabCurrentRow());
		if (selectLabItem!=null) {
			System.out.println("selectLabItem.getId().getReserveLabNo(): "+selectLabItem.getId().getReserveLabNo());
		}
		labAnswerItems = selectLabItem.retrieveReserveItemLabAnswersSort();
		}
	public void insertReserveLabAnswerLine(ActionEvent event) {
		System.out.println("con100:insertReserveLabAnswerLine");
	
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		
		ReserveItemLabAnswer aInsertLabAnswer = new ReserveItemLabAnswer();
		ReserveItemLabAnswerId aId = new ReserveItemLabAnswerId();
		
		aId.setReserveNo(reserve.getReserveNo());
		aId.setReserveLine(selectItem.getId().getReserveLine());
		aId.setReserveLabNo(selectLabItem.getId().getReserveLabNo());
		if (labAnswerItems == null) {
			labAnswerItems = new ArrayList();	
		}
		if (labAnswerItems.size() > 0) {
			ReserveItemLabAnswer aLabAnswer = labAnswerItems.get(labAnswerItems.size()-1);
			aId.setReserveLabAnswerNo(aLabAnswer.getId().getReserveLabAnswerNo()+1);
		} else {
			aId.setReserveLabAnswerNo(1);
		}
		aInsertLabAnswer.setId(aId);
		aInsertLabAnswer.setCreateDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
		aInsertLabAnswer.setCreateBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
		labAnswerItems.add(aInsertLabAnswer);
		selectLabItem.getReserveItemLabAnswers().add(aInsertLabAnswer);
	}
	public void insertReserveLineLabAnswerOk(ActionEvent event) {
		System.out.println("con100:insertReserveLineLabAnswerOk");
		System.out.println("selectLabItem.getId().getReserveLabNo(): "+selectLabItem.getId().getReserveLabNo());
		for (int i=0;i<labAnswerItems.size();i++) {
			if (i==0) {
				selectLabItem.setReserveLabDate(labAnswerItems.get(i).getReserveLabDate());
				selectLabItem.setRemark(labAnswerItems.get(i).getRemark());
			} else if (labAnswerItems.get(i).getReserveLabDate()!=null && labAnswerItems.get(i).getReserveLabDate().after(selectLabItem.getReserveLabDate())) {
				selectLabItem.setReserveLabDate(labAnswerItems.get(i).getReserveLabDate());
				selectLabItem.setRemark(labAnswerItems.get(i).getRemark());
			}
		}
	}
	
	public void insertReserveLineLabAnswerCancel(ActionEvent event) {
		System.out.println("con100:insertReserveLineLabAnswerCancel");
		System.out.println("selectLabItem.getId().getReserveLabNo(): "+selectLabItem.getId().getReserveLabNo());
		System.out.println("labAnswerItems: "+labAnswerItems.size());
		if (labAnswerItemsBefore != null) {
			System.out.println("labAnswerItemsBefore: "+labAnswerItemsBefore.size());
		}
		selectLabItem.setReserveItemLabAnswers(new HashSet<ReserveItemLabAnswer>(labAnswerItemsBefore));
	}
	
	public void insertReserveLineSaleOpen(ActionEvent event) {
		System.out.println("con100:insertReserveLineSaleOpen");
		insertSaleItem = new ReserveItemSale();
		ReserveItemSaleId id = new ReserveItemSaleId();
		id.setReserveNo(reserve.getReserveNo());
		id.setReserveLine(selectItem.getId().getReserveLine());
		insertSaleItem.setId(id);
	}
	
	public String insertReserveLineSaleSave() {
		System.out.println("con100:insertReserveLineSaleSave");
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		
		EntityManager em = EntityManagerHelper.getEntityManager();
		if (insertSaleItem.getId().getSaleOrder() == null || insertSaleItem.getId().getSaleOrder().equals("") ||
				insertSaleItem.getId().getSaleItem() == null || insertSaleItem.getId().getSaleItem().equals("")) {
			return null;
		}
		insertSaleItem.getId().setReserveNo(reserve.getReserveNo());
		insertSaleItem.getId().setReserveLine(selectItem.getId().getReserveLine());
		insertSaleItem.getId().setSaleItem(Formatting.leadingChar(insertSaleItem.getId().getSaleItem(), '0', 6));
		
		SaleDataDAO saleDataDAO = new SaleDataDAO();
		SaleDataId saleDataId = new SaleDataId();
		saleDataId.setSaleOrder(insertSaleItem.getId().getSaleOrder());
		saleDataId.setSaleItem(insertSaleItem.getId().getSaleItem());
		SaleData aSale = saleDataDAO.findById(saleDataId);
		if (aSale != null) {
			em.refresh(aSale);
			insertSaleItem.setSaleData(aSale);
			
			insertSaleItem.setCreateDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
			insertSaleItem.setCreateBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
			
			ReserveItemSaleGreige aSaleGreige = new ReserveItemSaleGreige();
			aSaleGreige.setReserveItemSale(insertSaleItem);
			aSaleGreige.setCommonDataId(new CommonDataId("", ""));
			saleItems.add(aSaleGreige);
			selectItem.getReserveItemSales().add(insertSaleItem);
			dyeItems.addAll(aSale.getCommonDatas());
		} else {
			FacesMessage facesMessage = new FacesMessage("Cannot find Sale Order: "+insertSaleItem.getId().getSaleOrder()+" "+insertSaleItem.getId().getSaleItem());
			facesContext.addMessage("con101Form", facesMessage);
		}
		insertSaleItem = new ReserveItemSale();
		ReserveItemSaleId id = new ReserveItemSaleId();
		insertSaleItem.setId(id);
		return null;
	}
	
	public void onchangeReserveLineSale(ActionEvent event) {
		System.out.println("con100:onchangeReserveLineSale");
		System.out.println(((SimpleRowKey)getSelectionSale().getKeys().next()).intValue());
		selectSaleItem = saleItems.get(((SimpleRowKey)getSelectionSale().getKeys().next()).intValue());
	}
	
	public void editReservreLineSaleSave(ActionEvent event) {
		System.out.println("con100:editReservreLineSaleSave");
		if (selectSaleItem.getCommonDataId().getProductionNo() != null && !selectSaleItem.getCommonDataId().getProductionNo().equalsIgnoreCase("")) {
			for (int i=0;i<greigeItems.size();i++) {
				ReserveItemGreige aItemGreige = greigeItems.get(i);
				if (selectSaleItem.getCommonDataId().getProductionNo().equals(aItemGreige.getCommonData().getId().getProductionNo())) {
					selectSaleItem.getReserveItemSale().setReserveItemGreige(aItemGreige);
					aItemGreige.getReserveItemSales().add(selectSaleItem.getReserveItemSale());
					break;
				}
			}
		} else {
			selectSaleItem.getReserveItemSale().setReserveItemGreige(null);
		}
	}
	
	public void insertReserveLineGreigeOpen(ActionEvent event) {
		System.out.println("con100:insertReserveLineGreigeOpen");
		insertGreigeItem = new ReserveItemGreige();
		CommonData aCommon = new CommonData();
		aCommon.setId(new CommonDataId(null,"0"));
		insertGreigeItem.setReserveItem(selectItem);
		insertGreigeItem.setCommonData(aCommon);
	}
	
	public String insertReserveLineGreigeSave() {
		System.out.println("con100:insertReserveLineGreigeSave");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		
		EntityManager em = EntityManagerHelper.getEntityManager();
		if ((insertGreigeItem.getCommonData().getId().getProductionNo() == null) || (insertGreigeItem.getCommonData().getId().getProductionNo().equals(""))) {
			return null;
		}
		insertGreigeItem.getCommonData().getId().setProductionNo(insertGreigeItem.getCommonData().getId().getProductionNo().toUpperCase());
		for (int i=0;i<greigeDeletes.size();i++) {
			ReserveItemGreige aGreige = greigeDeletes.get(i);
			if (aGreige.getCommonData().getId().getProductionNo().equals(insertGreigeItem.getCommonData().getId().getProductionNo())) {
				FacesMessage facesMessage = new FacesMessage(MessageUtil.returnMessage(this.getMessageBundle().getString("error12"), ":1", insertGreigeItem.getCommonData().getId().getProductionNo()));
				facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
				facesContext.addMessage("con101Form", facesMessage);
				return null;
			}
			
		}
		
		CommonDataDAO commonDataDAO = new CommonDataDAO();
		CommonDataId commonDataId = new CommonDataId();
		commonDataId.setProductionNo(insertGreigeItem.getCommonData().getId().getProductionNo());
		commonDataId.setSeq(insertGreigeItem.getCommonData().getId().getSeq());
		CommonData aCommon = commonDataDAO.findById(commonDataId);
		if (aCommon != null) {
			em.refresh(aCommon);
			insertGreigeItem.setCommonData(aCommon);
			insertGreigeItem.setCreateDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
			insertGreigeItem.setCreateBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
			greigeItems.add(insertGreigeItem);
			selectItem.getReserveItemGreiges().add(insertGreigeItem);
			selectItem.setGreigeChangeDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
			selectItem.setGreigeChangeBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));

			productionList.add(new SelectItem(aCommon.getId().getProductionNo(),aCommon.getId().getProductionNo()));
		} else {
			FacesMessage facesMessage = new FacesMessage(MessageUtil.returnMessage(this.getMessageBundle().getString("error11"), ":1", insertGreigeItem.getCommonData().getId().getProductionNo()));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con101Form", facesMessage);
		}
		insertGreigeItem = new ReserveItemGreige();
		return null;
	}
	
	public void onchangeGreige(ActionEvent event) {
		System.out.println("con100:onchangeGreige");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		selectItem.setGreigeChangeDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
		selectItem.setGreigeChangeBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
	}
	public void onchangeReserveLineGreige(ActionEvent event) {
		System.out.println("con100:onchangeReserveLineGreige");
		selectGreigeItem = greigeItems.get(((SimpleRowKey)getSelectionGreige().getKeys().next()).intValue());
	}
	
	public void deleteReserveItemGreige(ActionEvent event) {
		System.out.println("con100:deleteReserveItemGreige");
		//System.out.println("Delete: "+selectGreigeItem.getCommonData().getId().getProductionNo());
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		if (selectGreigeItem.getReserveItemSales() != null && selectGreigeItem.getReserveItemSales().size() <= 0) {
			greigeItems.remove(selectGreigeItem);
			selectItem.getReserveItemGreiges().remove(selectGreigeItem);
			if (selectGreigeItem.getRunning() != null) {
				greigeDeletes.add(selectGreigeItem);
			}
			for (int i=0;i<productionList.size();i++) {
				SelectItem aItem = (SelectItem)productionList.get(i);
				if (selectGreigeItem.getCommonData().getId().getProductionNo().equals(aItem.getValue())) {
					productionList.remove(aItem);
					break;
				}
			}
		} else {
			FacesMessage facesMessage = new FacesMessage(MessageUtil.returnMessage(this.getMessageBundle().getString("error13"), ":1", selectGreigeItem.getCommonData().getId().getProductionNo()));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con101Form", facesMessage);
		}
	}
	
	public void onchangeDyeing(ActionEvent event) {
		System.out.println("con100:onchangeDyeing");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		selectItem.setDyeingChangeDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
		selectItem.setDyeingChangeBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
	}
	public void onchangeReserveLineDye(ActionEvent event) {
		System.out.println("con100:onchangeReserveLineDye");
		selectDyeItem = dyeItems.get(((SimpleRowKey)getSelectionDye().getKeys().next()).intValue());
	}
	
	public void onchangeCustomer(ActionEvent event) {
		System.out.println("con100:onchangeCustomer");
		SapConnector connector = new SapConnector("ABAP_AS_WITHOUT_POOL", SAP_HOST, "tprfc", "tpcork");
		ZBapiGetCustomerList bapi = new ZBapiGetCustomerList(Formatting.generateCustomerNo(reserve.getCustomer()));
		try {
			bapi.execute(connector);
			if (bapi.getKna1Tab().getNumRows() > 0) {
				bapi.getKna1Tab().setRow(0);
				String aName = bapi.getKna1Tab().getString("NAME1")+" "+bapi.getKna1Tab().getString("NAME2");
				System.out.println("con100:onchangeCustomer:name: "+aName);
				reserve.setCustomerName(aName);
				reserve.setCustomer(Formatting.generateCustomerNo(reserve.getCustomer()));
			} else {
				reserve.setCustomerName("");
				FacesContext facesContext = FacesContext.getCurrentInstance();
				FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error10"));
				facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
				facesContext.addMessage("con101Form", facesMessage);
			}
		} catch (JCoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void onchangeProduction(ActionEvent event) {
		System.out.println("con100:onchangeProduction");
		Iterator<Object> iterator = getSelectionSale().getKeys();
		while (iterator.hasNext()) {
			SimpleRowKey key = (SimpleRowKey) iterator.next();
			ReserveItemSaleGreige aSaleGreige = saleItems.get(key.intValue());
			if (!aSaleGreige.getCommonDataId().getProductionNo().equalsIgnoreCase("")) {
				for (int i=0;i<greigeItems.size();i++) {
					ReserveItemGreige aItemGreige = greigeItems.get(i);
					if (aSaleGreige.getCommonDataId().getProductionNo().equals(aItemGreige.getCommonData().getId().getProductionNo())) {
						aSaleGreige.getReserveItemSale().setReserveItemGreige(aItemGreige);
						aItemGreige.getReserveItemSales().add(aSaleGreige.getReserveItemSale());
						break;
					}
				}
			} else {
				aSaleGreige.getReserveItemSale().setReserveItemGreige(null);
			}
		}
	}
	public void onchangeRaw(ActionEvent event) {
		System.out.println("con100:onchangeRaw");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		selectItem.setRawChangeDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
		selectItem.setRawChangeBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
	}
	public void save(ActionEvent event) {
		System.out.println("con100:save");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Application app = facesContext.getApplication();
		
		EntityManager em = EntityManagerHelper.getEntityManager();
		ReserveHeaderDAO headerDAO = new ReserveHeaderDAO();
		
		try {
			em.clear();
			ReserveHeader aReserveDB = headerDAO.findById(reserve.getReserveNo());
			System.out.println("Change Date Old:"+lastChangeDate);
			if (aReserveDB != null) {
				aReserveDB.setReserveNo(reserve.getReserveNo());
				em.refresh(aReserveDB);
				System.out.println("Change Date OldDB:"+aReserveDB.getChangeDate());
				if (!aReserveDB.getChangeDate().equals(lastChangeDate)) {
					FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error09"));
					facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
					facesContext.addMessage("con101Form", facesMessage);
					return;
				}
			}
		} catch (Exception e) {
			System.out.println("con100:save:Cannot get aReserveDB");
			e.printStackTrace();
			FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error07"));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con101Form", facesMessage);
			
			return;
		}
		
		if (reserve.getCustomer().equals("") || reserve.getCustomerName().equals("")) {
			FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error01"));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con101Form", facesMessage);
			return;
		}
		reserve.setCustomer(Formatting.generateCustomerNo(reserve.getCustomer()));
		reserve.getReserveItems().clear();
		for (int i=0;i<reserveItems.size();i++) {
			ReserveItem aReserveItem = reserveItems.get(i);
			aReserveItem.setMaterialNo(aReserveItem.getMaterialNo().toUpperCase());
			aReserveItem.setMaterialDesign(aReserveItem.getMaterialDesign().toUpperCase());
			if (!checkRequireItem(aReserveItem)) {
				FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error04"));
				facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
				facesContext.addMessage("con101Form", facesMessage);
				return;
//			} else {
//				aReserveItem.setChangeDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
//				aReserveItem.setChangeBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
			}
			reserve.getReserveItems().add(aReserveItem);
		}
		EntityManagerHelper.beginTransaction();
		try {
			reserve.setChangeDate(new Timestamp(Calendar.getInstance().getTime().getTime()));
			reserve.setChangeBy((String) app.createValueBinding("#{con000.userName}").getValue(facesContext));
			System.out.println("Change Date New:"+reserve.getChangeDate());
		
			reserve = headerDAO.update(reserve);
			List<ReserveItem> aItemList = reserve.retrieveItemsAll();
			boolean foundGreige;
			for (int i=0;i<greigeDeletes.size();i++) {
				foundGreige = false;
				ReserveItemGreige aItemGreige = greigeDeletes.get(i);
				ReserveItemGreigeDAO aReserveItemGreigeDAO = new ReserveItemGreigeDAO();
				aReserveItemGreigeDAO.delete(aItemGreige);
				for (int j=0;j<aItemList.size();j++) {
					ReserveItem aItem = aItemList.get(j);
					if (aItemGreige.getReserveItem().getId().getReserveNo().equals(aItem.getId().getReserveNo()) &&
							aItemGreige.getReserveItem().getId().getReserveLine().equals(aItem.getId().getReserveLine())) {
						Iterator aIter = aItem.getReserveItemGreiges().iterator();
						while (aIter.hasNext()) {
							ReserveItemGreige aOldGreige = (ReserveItemGreige)aIter.next();
							if (aItemGreige.getRunning().intValue() == aOldGreige.getRunning().intValue()) {
								aItem.getReserveItemGreiges().remove(aOldGreige);
								foundGreige = true;
								break;
							}
						}
						if (foundGreige) {
							break;
						}
					}
				}
				
			}
			//reserve = em.merge(reserve);
			em.flush();
			
			EntityManagerHelper.commit();
			
			greigeDeletes = new ArrayList();
			saleDeletes = new ArrayList();
			em.refresh(reserve);
			reserveItems = reserve.retrieveItemsAll();
			if (selectItem != null && getSelection().getKeys().hasNext()) {
				selectItem = reserveItems.get(((SimpleRowKey)getSelection().getKeys().next()).intValue());
				labItems = selectItem.retrieveReserveItemLabsSort();
				greigeItems = selectItem.retrieveReserveItemGreigesSort();
				dyeItems = selectItem.retrieveDyeProductions();
			}
			lastChangeDate = new Timestamp(reserve.getChangeDate().getTime());
			lastChangeDate.setNanos(0);
			changed = true;
			created = changed;
			
			FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("info01"));
			facesMessage.setSeverity(FacesMessage.SEVERITY_INFO);
			facesContext.addMessage("con101Form", facesMessage);
		} catch (Exception e) {
			System.out.println("con100:save:Cannot save data");
			e.printStackTrace();
			
			FacesMessage facesMessage = new FacesMessage(this.getMessageBundle().getString("error07"));
			facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
			facesContext.addMessage("con101Form", facesMessage);
			
			EntityManagerHelper.rollback();
		}
	}

	private boolean checkRequireItem(ReserveItem aReserveItem) {
		System.out.println("con100:checkRequireItem");
		if (aReserveItem.getMaterialDesign() == null || aReserveItem.getMaterialDesign().equals("")) {
			return false;
		}
		if (aReserveItem.getDivision() == null || aReserveItem.getDivision().equals("")) {
			return false;
		}
		if (aReserveItem.getReserveQty() == null || aReserveItem.getReserveQty() <= 0) {
			return false;
		}
		if (aReserveItem.getUom() == null || aReserveItem.getUom().equals("")) {
			return false;
		}
		if (aReserveItem.getDeliveryDate() == null) {
			return false;
		}
		if (aReserveItem.getStatus() == null || aReserveItem.getStatus()<= 0) {
			return false;
		}
		return true;
	}
	public String cancel() {
		System.out.println("con100:cancel");
		return "con100";
	}
	
	private ResourceBundle getMessageBundle() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ResourceBundle rb = ResourceBundle.getBundle(
				"com.tpc.control.message.ResourceBundle", facesContext
						.getViewRoot().getLocale());
		return rb;
	}
	
}
